export const getCustomConfig = () => {
    return {
        com: {
            prop: {
                span: {
                    type: Number
                },
                offset: {
                    type: Number
                },
                push: {
                    type: Number
                },
                comName: {
                    type: String,
                    default: "ElButton"
                },
                contentText: {
                    type: String
                },
                childNode: {
                    type: Array,
                    default: []
                },
                v_for: {
                    type: Array,
                    default: []
                },
                v_model: {
                    type: String
                },
                v_show: { type: String },
                v_html: { type: String },
                varys: {
                    type: Object,
                    default: {}
                }
            },
            formItemProps: {
                prop: {
                    type: String
                },
                // formProp: {
                //     type: String
                // }, //绑定属性 与data-key 对应
                label: {
                    type: String
                }, //item名称
                isRequired: {
                    type: String
                }, //必选 添加*样式 及校验函数 与rule 关联
                //rules
                required: {
                    type: Object
                },
                number: {
                    type: Object
                },
                custom: {
                    type: Object
                },
                minNumber: {
                    type: Object
                },
                ruleLabel: {
                    type: String
                }
            }
        },
        form: {
            prop: {
                "label-width": { type: String }, //表单域标签的宽度
                "label-position": { type: String }, //表单域标签的位置，如果值为 left 或者 right 时，则需要设置 label-width
                model: {
                    type: Object,
                    default: {}
                }, //数据
                rules: {
                    type: Object,
                    default: {}
                },
                template: {
                    type: Array,
                    default: []
                }
            }
        },
        row: {
            prop: {
                gutter: {
                    type: Number
                },
                components: {
                    type: Array,
                    default: []
                }
            }
        },
        global: {
            prop: {
                class: {
                    type: String
                }
                // style: {
                //     type: String
                // },
            }
        }
    }
}
export const toCamelCase = (str) => {
    // 将字符串按照 - 或 _ 进行分割
    const words = str.split(/[-_]/)
    // 将第一个单词保持不变，其余单词首字母大写后拼接
    const result = words.reduce((acc, curr, index) => {
        if (index === 0 && curr !== "el") {
            // 不对第一个单词进行修改
            return curr + acc
        }
        // 将首字母大写后拼接
        return acc + curr.charAt(0).toUpperCase() + curr.slice(1)
    }, "")
    return result
}
export const deepClone = (obj) => {
    if (obj === null) return null // 如果是 null 直接返回 null
    if (typeof obj !== "object") return obj // 如果 obj 没有子属性直接返回 obj

    let clone = Array.isArray(obj) ? [] : {}
    for (let key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            clone[key] = deepClone(obj[key]) // 递归调用 deepClone 进行深度拷贝
        }
    }
    return clone
}

/* 递归遍历 匹配属性 */
export const getItemByAttr = (
    target,
    arr,
    prop,
    childProp,
    once = true,
    deep = false,
    item = null,
    each = false
) => {
    if (!Array.isArray(arr)) return item
    let judgeFunc = (val) => {
        return val == target
    }

    if (typeof target === "function") {
        judgeFunc = target
    }
    if (once)
        arr.find((e, i) => {
            if (e) {
                if (judgeFunc(e[prop])) {
                    item = deep ? [arr, i] : e
                    return true
                } else {
                    let cprop = childProp
                    if (typeof childProp === "function") cprop = childProp(e, i, arr)
                    if (Array.isArray(e[cprop]) && e[cprop]?.length) {
                        let res = getItemByAttr(
                            target,
                            e[cprop],
                            prop,
                            childProp,
                            once,
                            deep,
                            item,
                            each
                        )
                        if (res) {
                            item = res
                            return true
                        }
                    }
                }
            }
        })
    else {
        if (!item) item = []
        if (each) {
            arr.forEach((e, i) => {
                if (e) {
                    let cprop = childProp
                    if (typeof childProp === "function") cprop = childProp(e, i, arr)
                    if (Array.isArray(e[cprop]) && e[cprop]?.length) {
                        let res = getItemByAttr(
                            target,
                            e[cprop],
                            prop,
                            childProp,
                            once,
                            deep,
                            item,
                            each
                        )
                        //item.push(...res)
                    }

                    if (judgeFunc(e[prop])) {
                        item.push(deep ? [arr, i] : e)
                    }
                }
            })
            return item
        } else
            arr.filter((e, i) => {
                if (e) {
                    let cprop = childProp
                    if (typeof childProp === "function") cprop = childProp(e, i, arr)
                    let res = false
                    if (Array.isArray(e[cprop]) && e[cprop]?.length) {
                        res = getItemByAttr(
                            target,
                            e[cprop],
                            prop,
                            childProp,
                            once,
                            deep,
                            item,
                            each
                        )
                    }
                    if (e[prop] == target) {
                        item.push(deep ? [arr, i] : e)
                        return true
                    }
                    return res
                }
            })
    }

    return item
}
export function debounce(fun, delay = 300) {
    let timer
    return function () {
        let ctx = this
        let args = arguments
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            timer = null
            fun.apply(ctx, args)
        }, delay)
    }
}
/* eslint-disable */
export const evalFunc = (str = "", varys = {}, args = [], debug = false) => {
    if (!str || typeof str !== "string") {
        console.log("执行错误", str);
        return null;
    }
    if (str.includes('varys.eee&&Object.keys(varys.eee).length!==0')) {
    }
    str = str.replaceAll("{varys}", JSON.stringify(varys));
    let computedVal = form?.value;
    if (computedVal) {
        str = str
            .replaceAll("form[", "form.value.[")
            .replaceAll("form.", "form.value.");
    }
    // str = str.replaceAll("{form}", JSON.stringify(form))
    args.forEach((e, i) => {
        let item = typeof e === "object" ? JSON.stringify(e) : e;
        str = str.replaceAll(`{${i}}`, item);
    });
    Object.keys(varys).forEach((k) => {
        let item =
            typeof varys[k] === "object" ? JSON.stringify(varys[k]) : varys[k];
        str = str.replaceAll(`{${k}}`, item);
    });
    try {
        let res = JSON.parse(str);
        debug && console.log("eval  " + str, res);
        return res;
    } catch (error) {
        try {
            let res = eval(str);
            debug && console.log("eval  " + str, res);

            return res;
        } catch (error) {
            debug && console.log(error);
            // console.log(this, "this");
        }
    }
};
export const validate = async (formConf) => {
    let res = await formConf.formRef().validate((valid) => {
        return valid;
    });
    if (!res) {
        ElMessage.error("参数错误，保存失败！");
        return false;
    } else return [res, formConf.props.model];
};
export const getDefaultForm = (form = {}, init = true) => {
    // 递归循环赋值
    init && (form = deepClone(form));
    Object.keys(form).forEach((k) => {
        let item = form[k];
        if (typeof item === "object" && item !== null) {
            form[k] = getDefaultForm(item, false);
        } else {
            form[k] = "";
        } //! 根据类型重置表单内容?
    });
    return form;
};
/* eslint-enable */
export const initForm = `new Proxy(
    {},
    {
      get: (target, prop, c) => {
        return {formConfStr}?.props?.model?.[prop];
      },
      set: (target, prop, value) => {
        try {
          {formConfStr}.props.model[prop] = value;
          return true;
        } catch (error) {
          console.log(error);
          return false;
        }
      },
    }
  )`;
const ruleConf = {
    required: (item) => {
        if (item.strict) {
            return {
                validator: (rule, value, callback) => {
                    if (!value || value === '') callback(new Error(`${item._ruleLabel}不能为空`))
                    else callback()
                },
                trigger: item.trigger || 'change'
            }
        }
        return { required: true, message: `${item._ruleLabel}不能为空`, trigger: item.trigger || 'change' }
    },
    number: (item) => {
        return { type: 'number', message: `${item._ruleLabel}必须为数字`, trigger: item.trigger || 'change' }
    },
    custom: (item) => {
        return { validator: item.validator, message: item.message, trigger: item.trigger || 'blur' }
    },
    minNumber: (item) => {
        return {
            validator: (rule, value, callback) => {
                if (value < item.minNumber) {
                    callback(new Error(`${item._ruleLabel}不能小于${item.minNumber}`))
                } else callback()
            }, trigger: "change",
        }

    }
}

//配置格式
// const formConf = {
//     filedConf: {
//         field1: {
//             rule: {
//                 required: {
//                     _ruleLabel: 'label'
//                 }
//             }
//         },
//         field2: {}

//     }
// }
export const getRules = (rules) => {
    let ruleObj = {}
    Object.keys(rules).forEach(k => {
        let field = k
        let fieldRulesArr = []
        Object.keys(rules[k]).forEach(rk => {
            if (typeof ruleConf[rk] == 'function')
                fieldRulesArr.push(ruleConf[rk](rules[k][rk]))
        });
        ruleObj[field] = fieldRulesArr
    });
    return ruleObj
}
window._getRules = getRules
